package org.springframework.context.support;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;

import java.util.Set;

/**
 * @Name ConversionServiceFactoryBean
 * @Description: 类型转换服务工厂加工 Bean [实现] 类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-11 17:45:45
 **/
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {
    private GenericConversionService conversionService;
    private Set<?> converters;

    public void setConverters(Set<?> converters) {
        this.converters = converters;
    }

    @Override
    public ConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        conversionService = new DefaultConversionService();
        registerConverters(converters, conversionService);
    }

    private void registerConverters(Set<?> converters, ConverterRegistry registry) {
        if (converters != null) {
            for (Object converter : converters) {
                if (converter instanceof Converter<?, ?>) {
                    registry.addConverter((Converter<?, ?>) converter);
                } else if (converter instanceof ConverterFactory<?, ?>) {
                    registry.addConverterFactory((ConverterFactory<?, ?>) converter);
                } else if (converter instanceof GenericConverter) {
                    registry.addGenericConverter((GenericConverter) converter);
                } else
                    throw new IllegalArgumentException("每一个类型转换器对象必须实现以下接口之一：Converter, ConverterFactory, GenericConverter");
            }
        }
    }
}

